package com.rongzhe.house.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.rongzhe.house.R;
import com.rongzhe.house.alipay.OrderInfoUtil2_0;
import com.rongzhe.house.alipay.PayResult;
import com.rongzhe.house.entity.PayContstract;
import com.rongzhe.house.entity.voo.HouseDetail;
import com.rongzhe.house.entity.voo.User;
import com.rongzhe.house.internet.DataListener;
import com.rongzhe.house.manager.HouseManager;
import com.rongzhe.house.manager.OrderManager;
import com.rongzhe.house.manager.UserManager;
import com.rongzhe.house.ui.UiControlInterface;
import com.rongzhe.house.ui.activity.OrderActivity;

import java.util.Map;

/**
 * Created by huang on 2018/1/4.
 */

public class OrderPresenter extends BasePresenter {
    private static final int SDK_PAY_FLAG = 1;

    public OrderPresenter(UiControlInterface uiControlInterface) {
        super(uiControlInterface);
    }

    @Override
    public void start(Intent intent) {
        final OrderActivity orderActivity = (OrderActivity) getUiControlInterface();
        orderActivity.setPayType(OrderManager.getInstance().getPayType());
        orderActivity.setHouseInfo(OrderManager.getInstance().getOrderHouseDetail());
        UserManager.getInstance().getUserInfo(new DataListener<User>() {
            @Override
            public void onSuccess(User data, String message) {
                orderActivity.setUserInfo(data);
            }

            @Override
            public void onFailed(Throwable error, String message) {

            }

            @Override
            public void onEnd() {

            }
        });
    }

    public void doSubmit() {
        createGoods();
    }

    private void createGoods() {
        getUiControlInterface().showProgress(getString(R.string.ordering_createing));
        //should not be null
        HouseDetail houseDetail = HouseManager.getInstance().getCurrentHouseDetail();
        String houseId = String.valueOf(houseDetail.getId());
        OrderManager.getInstance().getGoods(houseId, new DataListener() {
            @Override
            public void onSuccess(Object data, String message) {
                createOrder();
            }

            @Override
            public void onFailed(Throwable error, String message) {
                getUiControlInterface().dismissProgress();
                getUiControlInterface().showToast(message);
            }

            @Override
            public void onEnd() {

            }
        });
    }

    private void createOrder() {
        if (OrderManager.getInstance().getCurrentGoods() == null) {
            getUiControlInterface().dismissProgress();
            getUiControlInterface().showToast(getString(R.string.create_order_failed));
        } else {
            OrderManager.getInstance().createOrder(
                    OrderManager.getInstance().getCurrentGoods().getId(), new DataListener() {
                        @Override
                        public void onSuccess(Object data, String message) {
                            getSingStr();
                        }

                        @Override
                        public void onFailed(Throwable error, String message) {
                            getUiControlInterface().dismissProgress();
                            getUiControlInterface().showToast(message);
                        }

                        @Override
                        public void onEnd() {

                        }
                    });
        }
    }

    private void getSingStr() {
        if (TextUtils.isEmpty(OrderManager.getInstance().getOrderId())) {
            getUiControlInterface().dismissProgress();
            getUiControlInterface().showToast(getString(R.string.create_order_failed));
        } else {
            OrderManager.getInstance().getAliSign(OrderManager.getInstance().getOrderId(),
                    new DataListener<PayContstract>() {
                        @Override
                        public void onSuccess(PayContstract data, String message) {
                            getUiControlInterface().dismissProgress();
                            if (data.getCode() == 200) {
                                payV2(data.getData());
                            } else {
                                getUiControlInterface().showToast(
                                        getString(R.string.create_order_failed));
                            }
                        }

                        @Override
                        public void onFailed(Throwable error, String message) {
                            getUiControlInterface().dismissProgress();
                            getUiControlInterface().showToast(message);
                        }

                        @Override
                        public void onEnd() {
                        }
                    });
        }
    }

    /**
     * 支付宝支付业务
     */
    public void payV2(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask((Activity) getUiControlInterface());
                Map<String, String> result = alipay.payV2(data, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    getUiControlInterface().finish();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        getUiControlInterface().showToast("支付成功");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        getUiControlInterface().showToast("支付失败");
                    }
                    break;
                }
            }
        }
    };
}
